package org.example.service;


import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.example.mapper.OrderMapper;
import org.example.model.OrderInfo;
import org.example.model.ProductInfo;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Service
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RestTemplate restTemplate;


    //计数器
    /*private AtomicInteger counter = new AtomicInteger(1);

    private List<ServiceInstance> instances;

    @PostConstruct
    public void init() {
        instances = discoveryClient.getInstances("product-service");
    }
*/

    public OrderInfo selectOrderById(Integer orderId) {
        OrderInfo orderInfo = orderMapper.selectById(orderId);
        String url = "http://product-service/product/" + orderInfo.getProductId();
        log.info("远程调用的: url = {}", url);
        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
        orderInfo.setProductInfo(productInfo);
        return orderInfo;
    }



    /*public OrderInfo selectOrderById(Integer orderId) {
        OrderInfo orderInfo = orderMapper.selectById(orderId);
        String url = "http://product-service/product/" + orderInfo.getProductId();
        log.info("远程调用的: url = {}", url);
        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
        orderInfo.setProductInfo(productInfo);
        return orderInfo;
    }*/

    /*public OrderInfo selectOrderById(Integer orderId) {
        OrderInfo orderInfo = orderMapper.selectById(orderId);
        //String url = "http://127.0.0.1:9090/product/" + orderInfo.getProductId();
        init();
        //String uri = instances.get(0).getUri().toString();
        //计算轮流的index
        int index = counter.getAndIncrement() % instances.size();
        //获取uri
        String uri = instances.get(index).getUri().toString();
        String url = uri + "/product/" + orderInfo.getProductId();
        log.info("远程调用的: uri = {}", uri);
        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
        orderInfo.setProductInfo(productInfo);
        return orderInfo;
    }*/
}
